package cn.sciento.core.endpoint.client;

import cn.sciento.core.exception.ExceptionResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import cn.sciento.core.endpoint.HttpRequest;
import org.springframework.web.client.RestClientException;

public class StringHttpTransporter extends BaseHttpTransporter<String> {
  private final ObjectMapper objectMapper = new ObjectMapper();
  
  @Override
  public String transport(HttpRequest<String> request) {
    String body = super.transport(request);
    if (body == null) {
      return null;
    }
    try {
      ExceptionResponse response = this.objectMapper.readValue(body, ExceptionResponse.class);
      if (response != null && response.getFailed()) {
        throw new RestClientException("http transport failed, ExceptionResponse: " + response.getMessage());
      }
    } catch (IOException e) {
      if (e instanceof com.fasterxml.jackson.core.JsonParseException || e instanceof com.fasterxml.jackson.databind.JsonMappingException) {
        return body;
      }
      throw new RestClientException("response body parse failed", e);
    } 
    return body;
  }
}
